package com.achun.ximalayamvvm.view.fragment

import android.content.Intent
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.achun.ximalayamvvm.R
import com.achun.ximalayamvvm.RecommendListDetailActivity
import com.achun.ximalayamvvm.databinding.FragmentNullBinding
import com.achun.ximalayamvvm.databinding.FragmentRecommentBinding
import com.achun.ximalayamvvm.utils.Constants
import com.achun.ximalayamvvm.utils.LogUtil
import com.achun.ximalayamvvm.utils.ToastUtil
import com.achun.ximalayamvvm.utils.Uiloader
import com.achun.ximalayamvvm.view.adapter.RecommendListAdapter
import com.achun.ximalayamvvm.vm.MusicIndexViewModel
import com.achun.ximalayamvvm.vm.PlayerViewModel
import com.achun.ximalayamvvm.vm.RecommendDetailViewModel
import com.ximalaya.ting.android.opensdk.model.album.Album

class RecommendFragment : Fragment() {
    var frameLayout: FrameLayout? = null
    private var recommendListModel: MusicIndexViewModel? = null
    private var recommendListAdapter: RecommendListAdapter? = null
    lateinit var uiloader: Uiloader
    lateinit var recommentBinding: FragmentRecommentBinding
    private var isFirst = true
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        uiloader = object : Uiloader(requireContext()) {
            override fun retryOnclick() {
                recommendListModel?.loadrecommendList()
            }

            override fun getSuccessView(): View? {
                return createSuccessView(inflater, container)
            }
        }
        var recommentBinding = DataBindingUtil.inflate<FragmentNullBinding>(
            inflater,
            R.layout.fragment_null,
            container,
            false
        )
        var frameLayout = recommentBinding.root as FrameLayout
        frameLayout.addView(uiloader)
        //初始化viewmodel
        initViewHolder()
        //加载数据
        recommendListModel?.loadrecommendList()



        return recommentBinding!!.root
    }

    private fun initEvent(recommentBinding: FragmentRecommentBinding) {
        recommentBinding.upToFreshLayout.run {
            setOnRefreshListener { recommendListModel?.loadrecommendList() }
        }
        //列表项点击事件
        recommendListAdapter?.setOnclickItemListenter(object :
            RecommendListAdapter.OnClickItemListenter {
            @RequiresApi(Build.VERSION_CODES.P)
            override fun onclick(album: Album) {
                var instance = RecommendDetailViewModel.instance
                instance.setAlbums(album)
                instance.loadSubsced()
                startActivity(Intent(context, RecommendListDetailActivity::class.java))

            }

        })
    }

    private fun initViewHolder() {
        //创建viewModel实例
        recommendListModel = ViewModelProvider(this).get(MusicIndexViewModel::class.java)
        recommendListModel!!.requestCode.observe(viewLifecycleOwner) {
            when (it) {
                Constants.SUCCESS_CODE -> {
                    uiloader.updataStatus(Uiloader.UISTATUS.SUCCESS)
                }
                Constants.LOAD_CODE -> {
                    uiloader.updataStatus(Uiloader.UISTATUS.LOADING)
                }
                Constants.ERROR_CODE -> {
                    uiloader.updataStatus(Uiloader.UISTATUS.NETWORK_ERROR)
                }
            }
        }
        //创建观察器
        var observer = Observer<List<Album>> { it ->
            //第一次打开播放歌曲
            var setAlbum = RecommendDetailViewModel.instance.isSetAlbum
            if (!setAlbum) {
                var instance = RecommendDetailViewModel.instance
                instance.setAlbums(it[0])
                instance.firstLoad()
                //获取播放器实例,观察数据并播放第一首
                instance.firstTrackList.observe(viewLifecycleOwner) { tracks ->
                    if (isFirst) {
                        PlayerViewModel.instace.setTrack(tracks, 0)
                        isFirst = false
                    }
                }


            }

            ToastUtil.showToast("为你刷新了--${it.size}条数据")
            recommendListAdapter?.setDatas(it)
            recommentBinding.upToFreshLayout.run {
                isRefreshing = false
            }

        }
        //观察livedata
        recommendListModel!!.getrecommendList()?.observe(viewLifecycleOwner, observer)
    }

    private fun createSuccessView(inflater: LayoutInflater, container: ViewGroup?): View? {
        recommentBinding = DataBindingUtil.inflate<FragmentRecommentBinding>(
            inflater,
            R.layout.fragment_recomment,
            container,
            false
        )
        recommendListAdapter = RecommendListAdapter()
        recommentBinding.recommendListView.run {
            layoutManager = LinearLayoutManager(context)
            adapter = recommendListAdapter
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    itemPosition: Int,
                    parent: RecyclerView
                ) {
                    outRect.right = 20
                    outRect.left = 20
                    outRect.top = 20
                    outRect.bottom = 20
                }
            })
        }

        //初始化事件
        initEvent(recommentBinding)

        return recommentBinding.root
    }


    override fun onDestroyView() {
        super.onDestroyView()
        frameLayout?.removeAllViews()

    }
}